<template>
    <div class="cart">
        <div class="zi" style="width:100%;background: white;">
            <h3 style="text-align: center;background-color: white;">购物车</h3>
            <p style="color:gray;">自提点：{{ address }}</p>
        </div>
        <div class="miao">
            <div class="miaosha">
                <button style="border:none;background-color: rgb(242, 242, 242);margin-left: 20px;margin-bottom: 10px;">
                    <span style="float: left;color:red;">秒杀</span>
                    <van-count-down :time="time" format=" HH : mm : ss" @finish="handleCountdownFinish"
                        style="float: right;padding-left: 30px;" />
                </button>
                <van-cell-group>
                    <van-swipe-cell v-for="item in shopItems" :key="item._id">
                        <template #right>
                            <van-button size="small" type="danger" @click="deleteItem(item._id)">
                                删除
                            </van-button>
                        </template>
                        <div id="list_item">
                            <van-checkbox v-model="item.checked" @change="updateTotalPrice(item)"></van-checkbox>
                            <div id="item_img">
                                <img :src="item.img" alt="" style="width:100%;height:100%"
                                    @click="router.push(`/xiangs?_id=${item._id}`)">
                            </div>
                            <div id="item_con">
                                <div class="ctitle">{{ item.name }}</div>
                                <div class="cbtn">
                                    <button style="background:rgb(239, 128, 130);color:white;border:none">限购10件</button>
                                </div>
                                <div class="cfot">
                                    <div class="cfot_left">
                                        <span style="color:red;">￥{{ item.price }}</span> <br>
                                        <span class="del">{{ item.original }}</span>
                                    </div>
                                    <div class="cfot_right">
                                        <p>
                                            <button @click="subnum(item._id)" v-if="item.num > 1">-</button>
                                            <span>{{ item.num }}</span>
                                            <button @click="addnum(item._id)" :disabled="item.num >= 10">+</button>
                                        </p>
                                        <span v-if="item.num >= 10" style="color: red;">数量已达到最大限制</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </van-swipe-cell>
                </van-cell-group>
            </div>

            <div class="shi">
                <p> 失效商品</p>
                <div id="list_item" v-for="item in lastTwoExpiredItems" :key="item._id">
                    <van-checkbox v-model="isChecked" :disabled="true"></van-checkbox>
                    <div id="item_img">
                        <img src="https://pic.616pic.com/ys_img/00/11/69/zYoRthtBIl.jpg" alt=""
                            style="width:110px;height:110px">
                    </div>
                    <div id="item_con">
                        <div class="ctitle">{{ item.name }}</div>
                        <div>抱歉，秒杀商品已到期</div>
                        <button
                            style="margin-top: 30px;margin-left: 80px;background: white;border:1px solid gainsboro">到货提醒</button>
                    </div>
                </div>
            </div>

            <h3 style="text-align: center">为你推荐</h3>
            <div class="tui">
                <div id="list_items" v-for="item in randomList" :key="item._id">
                    <div id="item_imgs">
                        <img :src="item.img" alt="" style="width:100%;height:100%"
                            @click="router.push(`/xiang?_id=${item._id}`)">
                    </div>
                    <div id="item_cons">
                        <div class="ctitles">{{ item.name }}</div>

                        <div class="cbtns">
                            <button style="background-color:white;border:1px solid grey;">限购10件</button>
                        </div>
                        <div class="cfots">
                            <div class="cfot_lefts">
                                <span style="color:red;">￥{{ item.price }}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                <span class="dels">{{ item.original }}</span>
                                <span class="tu" @click="incrementQuantity(item)">
                                    <van-icon name="cart-o" size="20" color="red" :badge="item.num" />
                                </span>
                            </div>
                            <div class="cfot_rights">
                                <span v-if="item.num >= 10" style="color: red;">数量已达到最大限制</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <van-sticky position="bottom">
            <div class="footer">
                <van-checkbox v-model="isCheckAll" :indeterminate="isIndeterminate" @change="checkAllChange">
                    全选
                </van-checkbox>
                <div>
                    <span v-if="isCheckAll || hasSomeChecked">总计: {{ totalPrice }}</span><br />
                    <span v-if="isCheckAll || hasSomeChecked">为你节省: {{ shengPrice }}</span>
                </div>
                <van-button type="danger" @click="placeOrder">去下单({{ totalSelectedCount }})</van-button>
            </div>
            <div id="tabss">
            <TabsView/>
            </div>
        </van-sticky>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import TabsView from '../TabsView.vue';
const router = useRouter()
const time = ref(30 * 60 * 60 * 1000);
const isChecked = ref(true)
const shopItems = ref([]);
const address = ref('')
const payment = ref([])
onMounted(async () => {
    try {
        const { data } = await axios.get('http://localhost:3000/shop');
        shopItems.value = data.shop;
    } catch (error) {
        console.error('获取购物车数据失败：', error);
    }
    address.value = localStorage.getItem('address')
    console.log(address.value)
});
// 减少数量
const subnum = async (_id: string) => {
    await axios.put(`http://localhost:3000/subnum/${_id}`).then(() => {
        const item = shopItems.value.find(i => i._id === _id);
        if (item && item.num > 0) {
            item.num -= 1;
            updateTotalPrice();
        }
    });
};

// 增加数量
const addnum = async (_id: string) => {
    await axios.put(`http://localhost:3000/addnum/${_id}`).then(() => {
        const item = shopItems.value.find(i => i._id === _id);
        if (item) {
            item.num += 1;
            updateTotalPrice();
        }
    });
};
// 计算总价
const totalPrice = computed(() => {
    let total = 0;
    if (isCheckAll.value || hasSomeChecked.value) {
        shopItems.value.forEach(item => {
            if (item.checked) {
                total += item.price * item.num;
            }
        });
    }
    return total.toFixed(2);
});
// 计算节省了多少钱
const shengPrice = computed(() => {
    let total = 0;
    if (isCheckAll.value || hasSomeChecked.value) {
        shopItems.value.forEach(item => {
            if (item.checked) {
                total += (item.original - item.price) * item.num;
            }
        });
    }
    return total.toFixed(2);
});
// 全选复选框
const isCheckAll = ref(false);
const isIndeterminate = ref(false);
const updateCheckAllState = () => {
    const allChecked = shopItems.value.every(item => item.checked);
    const someChecked = shopItems.value.some(item => item.checked);
    isCheckAll.value = allChecked;
    isIndeterminate.value = !allChecked && someChecked;
};

const checkAllChange = (checked: boolean) => {
    shopItems.value.forEach(item => {
        item.checked = checked;
    });
    updateTotalPrice();
};

const hasSomeChecked = computed(() => {
    return shopItems.value.some(item => item.checked);
});

const updateTotalPrice = (item) => {
    console.log(item);
    payment.value.push(item)
    totalPrice.value;
    updateCheckAllState();
};
// 对去下单总数进行计算
const totalSelectedCount = computed(() => {
    return shopItems.value.filter(item => item.checked).reduce((total, item) => total + item.num, 0);
});

const placeOrder = async () => {
    await axios.post('http://localhost:3000/addding', payment.value);
    router.push('/ding');
}
// 随机展示四条数据
const randomList = ref([]);
const list1 = ref([])
const getList = async () => {
    let { data } = await axios.get('http://localhost:3000/list');
    list1.value = data.list
}
onMounted(() => {
    getList()
})
const selectRandomItems = () => {
    // 生成随机索引并获取四个随机项
    const indices = new Set<number>();
    while (indices.size < 4 && indices.size < list1.value.length) {
        indices.add(Math.floor(Math.random() * list1.value.length));
    }
    randomList.value = Array.from(indices).map(index => list1.value[index]);
};
watch(list1, () => {
    if (list1.value.length > randomList.value.length || list1.value.length < randomList.value.length) {
        selectRandomItems();
    }
});
// 点击图标加一
const incrementQuantity = (item: Item) => {
    if (item.num < 10) {
        item.num += 1;
    }
};
// 限时秒杀
const isExpired = ref(false)
const expiredItems = computed(() => {
    return list1.value.filter(item => item.isExpired)

})
console.log(list1.value);

const handleCountdownFinish = () => {
    list1.value.forEach(item => {
        item.isExpired = true
    })

}
const lastTwoExpiredItems = computed(() => {
    return list1.value.slice(-2);
});
// 向左滑，展示删除
const deleteItem = async (_id: string) => {
    const { data } = await axios.delete(`http://localhost:3000/delshop/${_id}`)

    if (data.code === 200) {
        const index = shopItems.value.findIndex(item => item._id === _id)
        if (index !== -1) {
            shopItems.value.splice(index, 1)
        }
        getList()
    }
};
</script>

<style scoped lang="scss">
.cart {
    width: 100%;
    padding-bottom: 50px;
    height: 100%;
    background: rgb(247, 247, 247);

    .footer {
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: space-between;
        padding: 10px;
        background-color: white;
        margin-top: 20px;
        z-index: 999;

        .van-checkbox {
            margin-right: 10px;
        }

        .van-button {
            margin-right: 10px;
        }

        h2 {
            font-size: 16px;
            margin: 0;
        }
    }
}

.miao {
    width: 90%;
    margin: 0 auto;
    background: rgb(247, 247, 247);
}

.miaosha {
    background: white;

}

#list_item {
    width: 90%;
    height: 145px;
    display: flex;
    justify-content: space-between;
    margin-top: 3px;
    border-bottom: 1px solid rgb(214, 214, 214);
    margin: 0 auto;
    background: white;

    #item_img {
        width: 110px;
        height: 110px;
    }

    #item_con {
        width: 50%;
        height: 100%;
        color: rgb(117, 117, 117);
        margin-left: 10px;

        .ctitle {
            width: 100%;
            height: 30px;
        }

        .cnew {
            width: 100%;
            height: 20px;
            color: red;
        }

        .cbtn {
            width: 100%;
            height: 30px;
            margin-top: 10px;
        }

        .cfot {
            width: 100%;
            height: 65px;
            display: flex;
            justify-content: space-between;
            margin-top: 5px;

            .cfot_left {
                width: 35%;
                height: 100%;

                .del {
                    height: 10px;
                    line-height: 10px;
                    text-decoration: line-through;
                }
            }

            .cfot_right {
                width: 65%;
                height: 100%;

                .join {
                    width: 90%;
                    height: 30px;
                    line-height: 30px;
                    background: red;
                    color: white;
                    border-radius: 20px;
                    text-align: center;
                    font-size: 14px;
                }
            }
        }
    }
}

.shi {
    width: 100%;
    margin: 0 auto;
    min-height: 380px;
    background: white;

    #list_item {
        width: 100%;
        height: 145px;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        border-bottom: 1px solid rgb(214, 214, 214);
    }

    #item_img {
        width: 110px;
        height: 110px;
    }

    #item_con {
        width: 60%;
        height: 100%;
        color: rgb(117, 117, 117);
        margin-left: 10px;

        .ctitle {
            width: 100%;
            height: 30px;
        }

        .cnew {
            width: 100%;
            height: 20px;
            color: red;
        }

        .cbtn {
            width: 100%;
            height: 30px;
            margin-top: 10px;
        }

        .cfot {
            width: 100%;
            height: 65px;
            display: flex;
            justify-content: space-between;
            margin-top: 5px;

            .cfot_left {
                width: 35%;
                height: 100%;

                .del {
                    height: 10px;
                    line-height: 10px;
                    text-decoration: line-through;
                }
            }

            .cfot_right {
                width: 65%;
                height: 100%;

                .join {
                    width: 90%;
                    height: 30px;
                    line-height: 30px;
                    background: red;
                    color: white;
                    border-radius: 20px;
                    text-align: center;
                    font-size: 14px;
                }
            }
        }
    }
}


.tui {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    background: white;
    justify-content: space-around;

    #list_items {
        width: 48%;
        height: 250px;
        margin-bottom: 20px;

        #item_imgs {
            width: 160px;
            height: 110px;
            // padding-left: 20px;
        }

        #item_cons {
            // padding-left: 20px;
            width: 100%;
            height: 100%;
            color: rgb(117, 117, 117);
            margin-left: 10px;

            .ctitles {
                width: 100%;
                height: 30px;
            }

            .cnews {
                width: 100%;
                height: 20px;
                color: red;
            }

            .cbtns {
                width: 100%;
                height: 30px;
                margin-top: 10px;
            }

            .cfots {
                width: 100%;
                height: 65px;
                margin-top: 5px;

                .cfot_lefts {
                    width: 50%;
                    height: 100%;
                    display: flex;
                    justify-content: space-between;

                    .dels {
                        height: 10px;
                        text-decoration: line-through;
                    }

                    .tu {
                        padding-left: 23px;
                    }
                }

                .cfot_rights {
                    width: 65%;
                    height: 100%;

                    .joins {
                        width: 90%;
                        height: 30px;
                        line-height: 30px;
                        background: red;
                        color: white;
                        border-radius: 20px;
                        text-align: center;
                        font-size: 14px;
                    }
                }
            }
        }
    }

    #list_items>div {
        width: 48%;
        height: 145px;
        margin-bottom: 20px;
        box-sizing: border-box;
    }

}
</style>